package com.ll.blog.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ll.blog.Exception.BlogException;
import com.ll.blog.annotation.CheckWord;
import com.ll.blog.common.ApiResponse;
import com.ll.blog.common.IPUtils;
import com.ll.blog.contant.ExceptionEnum;
import com.ll.blog.contant.TypeEnum;
import com.ll.blog.entity.Content;
import com.ll.blog.entity.User;
import com.ll.blog.filter.UserFilter;
import com.ll.blog.model.query.PageQuery;
import com.ll.blog.model.res.ContentListRes;
import com.ll.blog.model.res.PageDto;
import com.ll.blog.service.IContentService;
import com.ll.blog.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * 评论模块
 *
 * @since 2023-10-25
 */
@Validated
@RestController
public class ContentController {
    @Resource
    private IContentService contentService;
    @Autowired
    IUserService userService;

    /**
     * 评论接口
     *
     * @param username  用户名
     * @param articleId 文章id
     * @param avatar    头像
     * @param content   内容
     * @param PersonId  父评论id
     */
    @PostMapping("/comment/")
    @CheckWord(Field = "content")
    public ApiResponse Comment(
                               @NotEmpty(message = "用户名不能为空") String username,
                               @NotNull(message = "文章id不能为空") Integer articleId,
                               @NotEmpty(message = "评论内容不能为空") String content,
                               @RequestParam(required = false) String avatar,
                               @RequestParam(defaultValue = "0") int PersonId,
                               HttpServletRequest request
    ) {

        Content saved = saveData(TypeEnum.CONTENT,null, username, articleId, content, avatar, PersonId, request);
        if (saved==null) {
            return ApiResponse.error(ExceptionEnum.SAVE_ERROR);
        }
        return ApiResponse.success(saved);
    }

    /**
     * 留言接口（普通用户）
     *
     * @param username  用户名
     * @param avatar    头像
     * @param content   内容
     * @param PersonId  父评论id
     */
    @PostMapping("/message/")
    @CheckWord(Field = "content")
    public ApiResponse saveMessage(
            @NotEmpty(message = "用户名不能为空") String username,
            @NotEmpty(message = "评论内容不能为空") String content,
            @RequestParam(required = false) String avatar,
            @RequestParam(defaultValue = "0") int PersonId,
            HttpServletRequest request
    ) {
        Content saved = saveData(TypeEnum.MESSAGE,null, username, null, content, avatar, PersonId, request);
        if (saved==null) {
            return ApiResponse.error(ExceptionEnum.SAVE_ERROR);
        }
        return ApiResponse.success(saved);
    }


    private Content saveData(TypeEnum type, Integer userId, String username, Integer articleId, String content, String avatar, int PersonId, HttpServletRequest request) {
        if (PersonId != 0) {
            Content c = contentService.getById(PersonId);
            if (c==null){
                return null;
            }
        }
        String ip = IPUtils.getIpAddr(request);
        Content c = new Content();
        c.setIp(ip);
        c.setContent(content);
        c.setArticleId(articleId);
        c.setUsername(username);
        c.setParentsId(PersonId);
        c.setAvatar(avatar);
        c.setType(type);
        c.setUserId(userId);
        boolean saved = contentService.save(c);
        if (saved){
            return c;
        }
        return null;
    }



    /**
     * 登录用户评论
     *
     * @param articleId 文章id
     * @param content   内容
     * @param PersonId  父评论id
     */
    @CheckWord(Field = "content")
    @PostMapping("/comment/user")
    public ApiResponse release(@NotNull(message = "文章id不能为空") Integer articleId,
                               @NotEmpty(message = "评论内容不能为空") String content,
                               @RequestParam(defaultValue = "0") int PersonId,
                               HttpServletRequest request) {


        Integer userId = UserFilter.getUser();
        Content saved = saveData(TypeEnum.CONTENT, userId, null, articleId, content, null, PersonId, request);
        if (saved==null) {
            ApiResponse.error(ExceptionEnum.SAVE_ERROR);
        }

        return ApiResponse.success(saved);
    }


    /**
     * 登录用户留言
     *
     * @param content   内容
     * @param PersonId  父留言id
     */
    @CheckWord(Field = "content")
    @PostMapping("/message/user")
    public ApiResponse MessageByUser(@NotEmpty(message = "留言内容不能为空") String content,
                               @RequestParam(defaultValue = "0") int PersonId,
                               HttpServletRequest request) {


        Integer userId = UserFilter.getUser();
        Content saved = saveData(TypeEnum.MESSAGE, userId, null, null, content, null, PersonId, request);
        if (saved==null) {
            ApiResponse.error(ExceptionEnum.SAVE_ERROR);
        }

        return ApiResponse.success(saved);
    }

//    /**
//     * 更新评论
//     *
//     * @param id  评论id
//     * @param req 要更新的内容
//     */
//    @PutMapping("/admin/content/{id}")
//    public ApiResponse update(@PathVariable int id, ArticleQuery.ContentReq req) {
//        Content content = new Content();
//        BeanUtils.copyProperties(req, content);
//        content.setId(id);
//        boolean b = contentService.updateById(content);
//        if (!b) {
//            return ApiResponse.error(ExceptionEnum.UPDATE_ERROR);
//        }
//        return ApiResponse.success("更新成功");
//    }

    /**
     * 评论查询接口
     *
     * @param id 文章id
     */

    @GetMapping("/comment/{id}")
    public ApiResponse getByPage(@PathVariable Integer id, PageQuery query) {
        PageDto<ContentListRes> page = contentService.getContentByPage(id,TypeEnum.CONTENT, query);
        return ApiResponse.success(page);
    }


    /**
     * 留言查询接口
     */
    @Cacheable("Messagepage")
    @GetMapping("/message")
    public ApiResponse getMessageByPage( PageQuery query) {
        PageDto<ContentListRes> page = contentService.getContentByPage(null,TypeEnum.MESSAGE, query);
        return ApiResponse.success(page);
    }

    /**
     * 查询所有留言接口
     */
    @Cacheable("messageAll")
    @GetMapping("/message/all")
    public ApiResponse getMessageAll() {
        List<Content> list = contentService.list(new LambdaQueryWrapper<Content>().eq(Content::getType, 0).eq(Content::getParentsId,0));
        for (Content content : list) {
            if (content.getUsername()==null){
                User user = userService.getById(content.getUserId());
                content.setUsername(user.getUsername());
            }
        }
        return ApiResponse.success(list);
    }



    /**
     * 删除评论接口（单个）
     *
     * @param id 评论id
     * @return
     */
    @DeleteMapping("/admin/comment/{id}")
    @Transactional
    public ApiResponse del(@PathVariable Integer id) {
        Content content = contentService.getById(id);
        if (content == null) {
            return ApiResponse.error(ExceptionEnum.DELETE_ERROR);
        }
        ArrayList<Integer> list = new ArrayList<>();
        getlist(id, list,TypeEnum.CONTENT);
        list.add(id);
        boolean b = contentService.removeByIds(list);
        if (!b) {
            return ApiResponse.error(ExceptionEnum.DELETE_ERROR);
        }

        return ApiResponse.success("删除成功");
    }

    /**
     * 删除评论接口多个
     *
     * @param list 评论id列表
     * @return
     */
    @Transactional
    @DeleteMapping("/admin/comment/")
    public ApiResponse delMore(@RequestParam List<Integer> list) {
        ArrayList<Integer> l = new ArrayList<>();
        for (Integer i : list) {
            getlist(i, l,TypeEnum.CONTENT);
        }
        l.addAll(list);
        HashSet<Integer> set = new HashSet<>(l);
        l.clear();
        l.addAll(set);
        boolean b = contentService.removeBatchByIds(l);
        if (!b) {
            throw new RuntimeException();
        }
        return ApiResponse.success("删除成功");
    }


    /**
     * 删除留言接口（单个）
     *
     * @param id 评论id
     * @return
     */
    @DeleteMapping("/admin/message/{id}")
    @Transactional
    public ApiResponse delMessage(@PathVariable Integer id) {
        Content content = contentService.getById(id);
        if (content == null) {
            return ApiResponse.error(ExceptionEnum.DELETE_ERROR);
        }
        ArrayList<Integer> list = new ArrayList<>();
        getlist(id, list,TypeEnum.MESSAGE);
        list.add(id);
        boolean b = contentService.removeByIds(list);
        if (!b) {
            return ApiResponse.error(ExceptionEnum.DELETE_ERROR);
        }

        return ApiResponse.success("删除成功");
    }

    /**
     * 删除留言接口多个
     *
     * @param list 评论id列表
     * @return
     */
    @Transactional
    @DeleteMapping("/admin/message/")
    public ApiResponse delMoreMessage(@RequestParam List<Integer> list) {
        ArrayList<Integer> l = new ArrayList<>();
        for (Integer i : list) {
            getlist(i, l,TypeEnum.MESSAGE);
        }
        l.addAll(list);
        HashSet<Integer> set = new HashSet<>(l);
        l.clear();
        l.addAll(set);
        boolean b = contentService.removeBatchByIds(l);
        if (!b) {
            return ApiResponse.error(ExceptionEnum.DELETE_ERROR);
        }
        return ApiResponse.success("删除成功");
    }



    private void getlist(Integer id, List<Integer> list,TypeEnum type) {
        List<Content> list1 = contentService.list(new LambdaQueryWrapper<Content>().eq(Content::getParentsId, id));
        if (!list1.isEmpty()) {
            for (Content content : list1) {
                if (content.getType() != type){
                    throw new BlogException(ExceptionEnum.MAKE_ERROR);
                }
                list.add(content.getId());
                getlist(content.getId(), list,type);
            }
        }
    }




}
